package flc.ast.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;

import java.util.ArrayList;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.AppInformation;
import flc.ast.bean.StatisticsInfo;
import flc.ast.databinding.ActivityUseStateBinding;
import flc.ast.view.XYMarkerView;
import stark.common.basic.constant.Extra;
import stark.common.basic.utils.IntentUtil;

public class UseStateActivity extends BaseAc<ActivityUseStateBinding> implements OnChartValueSelectedListener {

    private int style = StatisticsInfo.DAY;
    ArrayList<AppInformation> ShowList;
    boolean usehour = false;
    protected BarChart mChart;
    private int mCurrentType;

    @Override
    protected int onCreate() {
        return R.layout.activity_use_state;
    }

    @Override
    protected void initView() {
        mDataBinding.ivUseStateBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.tvToday.setOnClickListener(this);
        mDataBinding.tvWeek.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.tvToday) {
            mCurrentType = 0;
            clearSelection();
            mDataBinding.tvToday.setTextColor(Color.parseColor("#FFFFFF"));
            mDataBinding.tvToday.setBackgroundColor(Color.parseColor("#797CDB"));
            getData();
        } else if (id == R.id.tvWeek) {
            mCurrentType = 1;
            clearSelection();
            mDataBinding.tvWeek.setTextColor(Color.parseColor("#FFFFFF"));
            mDataBinding.tvWeek.setBackgroundColor(Color.parseColor("#797CDB"));
            getData();
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        switch (mCurrentType) {
            case 0:
                style = StatisticsInfo.DAY;
                break;
            case 1:
                style = StatisticsInfo.WEEK;
                break;
            case 2:
                style = StatisticsInfo.MONTH;
                break;
            case 3:
                style = StatisticsInfo.YEAR;
                break;
            default:
                break;
        }
        StatisticsInfo statisticsInfo = new StatisticsInfo(this, style);
        ShowList = statisticsInfo.getShowList();
        usehour = getLagerestTime() > 300;
        mChart = (BarChart) findViewById(R.id.barchart);
        mChart.setOnChartValueSelectedListener(this);

        mChart.setDrawBarShadow(false);
        mChart.setDrawValueAboveBar(true);

        mChart.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mChart.setMaxVisibleValueCount(60);

        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);

        mChart.setDrawGridBackground(false);
        // mChart.setDrawYLabels(false);

        ValueFormatter xAxisFormatter = new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                int i = (int) value;
                if (ShowList.size() > i) {
                    if (i >= 6) return "其他应用";
                    else {
                        String str = ShowList.get(i).getLabel();
                        if (str != null && str.length() <= 4) return str;
                        else if (str != null && str.length() >= 3)
                            return (str.substring(0, 3) + "..");
                        else return "";
                    }
                } else return "";
            }
        };
        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(7);
        xAxis.setTextColor(Color.WHITE);
        xAxis.setValueFormatter(xAxisFormatter);

        ValueFormatter custom = new ValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
//                long i = (long)value;
//                i = i * ((YLength  / 1000 / 60 + 20) / 60 ) * 10;
                if (usehour) return (int) value + "hour";
                else return (int) value + "min";
            }
        };

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setLabelCount(8, false);
        leftAxis.setValueFormatter(custom);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(15f);
        leftAxis.setTextColor(Color.WHITE);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        YAxis rightAxis = mChart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setLabelCount(8, false);
        rightAxis.setValueFormatter(custom);
        rightAxis.setSpaceTop(15f);
        rightAxis.setTextColor(Color.WHITE);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setForm(Legend.LegendForm.SQUARE);
        l.setFormSize(9f);
        l.setTextSize(11f);
        l.setXEntrySpace(4f);
        l.setTextColor(Color.WHITE);
        // l.setExtra(ColorTemplate.VORDIPLOM_COLORS, new String[] { "abc",
        // "def", "ghj", "ikl", "mno" });
        // l.setCustom(ColorTemplate.VORDIPLOM_COLORS, new String[] { "abc",
        // "def", "ghj", "ikl", "mno" });

        XYMarkerView mv = new XYMarkerView(this, xAxisFormatter);
        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv); // Set the marker to the chart

        setDataBarChart();
    }

    private void setDataBarChart() {
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();
        if (ShowList.size() < 6) {
            for (int i = 0; i < ShowList.size(); i++) {
                float value;
                if (usehour)
                    value = (float) (1.0 * ShowList.get(i).getUsedTimebyDay() / 1000 / 60 / 60);
                else value = (float) (1.0 * ShowList.get(i).getUsedTimebyDay() / 1000 / 60);
                yVals1.add(new BarEntry(i, value));
            }
        } else {
            for (int i = 0; i < 6; i++) {
                float value;
                if (usehour)
                    value = (float) (1.0 * ShowList.get(i).getUsedTimebyDay() / 1000 / 60 / 60);
                else value = (float) (1.0 * ShowList.get(i).getUsedTimebyDay() / 1000 / 60);
                yVals1.add(new BarEntry(i, value));
            }
            long otherTime = 0;
            for (int i = 6; i < ShowList.size(); i++) {
                otherTime += ShowList.get(i).getUsedTimebyDay();
            }
            if (usehour)
                yVals1.add(new BarEntry(6, (float) (1.0 * otherTime / 1000 / 60 / 60)));
            else
                yVals1.add(new BarEntry(6, (float) (1.0 * otherTime / 1000 / 60)));
        }
        BarDataSet set1;

        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "Different APPs");
            set1.setColors(ColorTemplate.MATERIAL_COLORS);

            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);

            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
            data.setBarWidth(0.9f);

            mChart.setData(data);
        }
        mChart.invalidate();
    }


    private double getLagerestTime() {
        double time = 0;
        for (AppInformation appinformation : ShowList) {
            if (1.0 * appinformation.getUsedTimebyDay() / 1000 / 60 > time)
                time = 1.0 * appinformation.getUsedTimebyDay() / 1000 / 60;
        }
        return time;
    }

    protected RectF mOnValueSelectedRectF = new RectF();

    @Override
    public void onValueSelected(Entry e, Highlight h) {
        if (e == null)
            return;

        RectF bounds = mOnValueSelectedRectF;
        mChart.getBarBounds((BarEntry) e, bounds);
        MPPointF position = mChart.getPosition(e, YAxis.AxisDependency.LEFT);

        Log.i("bounds", bounds.toString());
        Log.i("position", position.toString());

        Log.i("x-index",
                "low: " + mChart.getLowestVisibleX() + ", high: "
                        + mChart.getHighestVisibleX());

        MPPointF.recycleInstance(position);
    }

    @Override
    public void onNothingSelected() {

    }

    private void clearSelection() {
        mDataBinding.tvToday.setTextColor(Color.parseColor("#808080"));
        mDataBinding.tvToday.setBackgroundColor(Color.parseColor("#323364"));
        mDataBinding.tvWeek.setTextColor(Color.parseColor("#808080"));
        mDataBinding.tvWeek.setBackgroundColor(Color.parseColor("#323364"));
    }

}